package com.tuo51.observation.controller;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import com.tuo51.core.domain.staffs.Staff;
import com.tuo51.core.service.StaffService;
import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.foudation.query.EvaluateQuery;
import com.tuo51.observation.domain.ObservatePoint;
import com.tuo51.observation.domain.ObservateRecord;
import com.tuo51.observation.service.ObservationService;
import com.tuo51.observation.vo.observation.ObservationRecordChoiceVO;
import com.tuo51.observation.vo.observation.ObservationVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

import static com.tuo51.foudation.constant.RequestConstant.TICKET;


@RestController
@RequestMapping("/oapi/observation")
@Api(value = "/oapi/observation", tags = "观测点 - 操作员")
public class OBObservationController {

    @Autowired
    private MemVerificationCache cache;

    @Autowired
    private ObservationService observationService;

    @Autowired
    private StaffService staffService;

    @RequestMapping("/records")
    @ApiOperation(value = "根据宝宝 id 获取观测点记录",httpMethod = "GET")
    public StatusResponse records(@RequestHeader(TICKET) String ticket, EvaluateQuery pagerQuery) {
        String staffId = cache.getStaffId(ticket);

        Page<ObservateRecord> records = observationService.getRecords(staffId, pagerQuery);

        return StatusResponse.success(records);
    }

    @RequestMapping("/list_by_children")
    @ApiOperation(value = "根据宝宝 id 获取观测点模板列表",httpMethod = "GET")
    public StatusResponse listByChildren(@RequestHeader(TICKET) String ticket, String childrenId) {
        String staffId = cache.getStaffId(ticket);

        List<ObservatePoint> observationList = observationService.getObservatePointsByChildrenId(staffId, childrenId);

        ObservateRecord record = observationService.getTodayFinishedRecords(staffId, childrenId);
        final Map<String, ObservationRecordChoiceVO> cache = (record != null && record.getResult() != null)
                ? record.getResult().stream().collect(Collectors.toMap(ObservationRecordChoiceVO::getId, o->o))
                : new HashMap();

        List<ObservationVO> result = observationList.stream().map(
                k -> {
                    ObservationVO ret = ObservationVO.of(k);

                    ObservationRecordChoiceVO choice = cache.get(ret.getId());

                    ret.getOptions().stream().forEach(p->{
                        p.setSelected(choice != null && choice.getOptionId() == p.getId());
                    });

                    return ret;
                }
        ).collect(Collectors.toList());

        Map ret = null;
        if (record != null){
            ret = ImmutableMap.of("list", result, "record", record);
        }else{
            ret = ImmutableMap.of("list", result);
        }

        return StatusResponse.success(ret);
    }

    @RequestMapping("/list_by_month")
    @ApiOperation(value = "根据月龄（能 parseFloat）获取观测点模板列表",httpMethod = "GET")
    public StatusResponse listByMonth(@RequestHeader(TICKET) String ticket, String month) {
        String staffId = cache.getStaffId(ticket);

        Float actualMonth = Float.parseFloat(month);

        List<ObservatePoint> observationList = observationService.getObservatePointsByMonth(actualMonth);

        List<ObservationVO> result = observationList.stream().map(k->ObservationVO.of(k)).collect(Collectors.toList());

        return StatusResponse.success(result);
    }

    @PostMapping("/add_record")
    @ApiOperation(value = "增加观测点记录, observationJson [{\"pointId\":pointId, \"img\":imgURL, option: {{\"optionId\":optionid, \"title\":optionTitle, \"score\":optionScore}}, ...]  ",httpMethod = "POST")
    public StatusResponse add(@RequestHeader(TICKET) String ticket,
                              String childrenId,
                              String observationJson) {

        List list = JSON.parseArray(observationJson);

        Staff staff = cache.getStaff(ticket);

        Boolean result = observationService.addObservationRecord(staff, childrenId, list);

        return StatusResponse.success(result);
    }

    @RequestMapping("observation_upload")
    @ApiOperation(value = "上传观测点图像记录",httpMethod = "POST")
    public StatusResponse observationUpload(Integer mediaType, MultipartFile[] files) {
        String imgUrl =  observationService.observationUpload(mediaType, files);
        return StatusResponse.success(imgUrl);
    }

}
